package cn.itsource.pethome.system.dictionary.controller;

import cn.itsource.pethome.system.dictionary.domain.DictionaryType;
import cn.itsource.pethome.system.dictionary.query.DictionaryTypeQuery;
import cn.itsource.pethome.system.dictionary.service.IDictionaryTypeService;
import cn.itsource.pethome.utils.AjaxResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author:R
 * @Date:2023/1/5 19:42
 * Description
 */
@RestController
@RequestMapping("/dtype")
@Api(value = "数据字典类型的API",description="数据字典类型的CRUD功能")
public class DictionaryTypeController {
    @Autowired
    private IDictionaryTypeService iDictionaryTypeService;

    @GetMapping
    @ApiOperation(value = "查询全部数据字典信息")
    public List<DictionaryType> findAll(){
        return iDictionaryTypeService.findAll();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询一条数据字典信息")
    public DictionaryType findOne(@PathVariable("id") Long id){
        return iDictionaryTypeService.findOne(id);
    }

    @PostMapping
    @ApiOperation(value = "高级查询")
    public AjaxResult findQuery(@RequestBody DictionaryTypeQuery typeQuery){
        try {
            List<DictionaryType> query = iDictionaryTypeService.findQuery(typeQuery);
            Long aLong = iDictionaryTypeService.countPage(typeQuery);
            return AjaxResult.success().setData(query).setTotal(aLong);
        }catch (Exception e){
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @PutMapping
    @ApiOperation(value = "新增方法【有id则为修改】")
    public AjaxResult save(@RequestBody DictionaryType dictionaryType){
        try {
            if (dictionaryType.getId() == null){    //新增
                iDictionaryTypeService.add(dictionaryType);
                return AjaxResult.success().setMsg("添加成功！");
            }else {
                iDictionaryTypeService.update(dictionaryType);
                return AjaxResult.success().setMsg("修改成功！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除数据字典信息")
    public AjaxResult del(@PathVariable("id") Long id){
        try {
            iDictionaryTypeService.delete(id);
            return AjaxResult.success().setMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }

    @PatchMapping
    public AjaxResult batch(@RequestBody List<Long> ids){
        try {
            iDictionaryTypeService.batchDel(ids);
            return AjaxResult.success().setMsg("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.error().setMsg(e.getMessage());
        }
    }
}
